#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# python 3.8.10 脚本编码utf8 20250816
# pyqt.py autoinstallv5_pyqt.py

""" 
- 20250817
mac中 pyenv local环境python命令提示无效
环境变量配置问题
确保 ~/.zshrc 或 ~/.bashrc 包含：
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
source ~/.zshrc  # 或 source ~/.bashrc   

win10 管理员权限重装 
scoop install pyenv
pyenv install 3.8.10
pyenv version
cd 当前目录 
pyenv local 3.8.10 #创建文件.python-version 控制项目中的版本
python -m venv .venv #创建虚拟环境
.venv\Scripts\Activate.ps1 #激活虚拟环境
pip install 安装包
"""

#获取脚本当前路径
from  pathlib import Path
current_file_path = Path(__file__)
current_directory = current_file_path.parent

# 获取注册表键值 pip install pywin32
import win32con,win32api 
def get_Reg_key(path,key_):
    reg_root = win32con.HKEY_LOCAL_MACHINE
    #reg_root = win32con.HKEY_CLASSES_ROOT
    reg_path = r'%s' % path
    reg_flags = win32con.KEY_READ | win32con.KEY_WOW64_64KEY
    # 读取键值
    key = win32api.RegOpenKey(reg_root, reg_path, 0, reg_flags)
    value, key_type = win32api.RegQueryValueEx(key, key_)
    
    #关闭键
    win32api.RegCloseKey(key)
    return {"value":value}

    # 测试注册表
try:
    reg=get_Reg_key("SOFTWARE\Classes\CATIA.Part\shell\open\command","")
except Exception as e:  
    print("找不到注册表信息，请检查Catia是否安装正确")
    print(e)
else:
    print(reg)


#生成资源文件目录访问路径 转成二进制保存文件，暂时不需要
import sys
def resource_path(relative_path):
    if getattr(sys, 'frozen', False): #是否Bundle Resource
        base_path = sys._MEIPASS
    else:
        base_path = Path('.').resolve()
    return base_path / relative_path

dir_setting = resource_path(Path("res").resolve()/"CATEnv2019")


# 按进程名终止进程
import win32api
import win32con
import win32com.client
def terminate_process_by_name(process_name):
    # 获取所有运行的进程
    WMI = win32com.client.GetObject('winmgmts:')
    processes = WMI.ExecQuery(f'SELECT * FROM Win32_Process WHERE Name="{process_name}"')

    for process in processes:
        process_id = process.Properties_('ProcessId').Value
        try:
            handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, process_id)
            win32api.TerminateProcess(handle, -1)
            win32api.CloseHandle(handle)
        except Exception as e:
            print(f"Failed to terminate {process_name} with PID {process_id}. Error: {e}")


# 启动一次软件并终止
import subprocess
def run_demo_exe(fpath,timewait):
    # global timeWait
    myPopenObj = subprocess.Popen([fpath], shell=True)
    try:
        myPopenObj.wait(timeout=timewait)
        # myPopenObj.wait()
        # if psutil.pid_exists(myPopenObj.pid) and psutil.pid_exists(myPopenObj.pid) in psutil.pids():
        #     print("程序运行")
    except Exception as e:
        #杀掉进程
        print("===== process timeout ======")
        myPopenObj.kill()
        myPopenObj.terminate()
        # myPopenObj.TerminateProcess()
        terminate_process_by_name("CNEXT.exe")
        # os.system("taskkill /im CNEXT.exe") 
        return None

# 获取桌面路径
def get_desk_p():
    home = Path.home()
    desktop = home / "Desktop"
    return desktop
    # https://blog.csdn.net/weixin_44224529/article/details/92393304


# 使用rglob遍历目录中的所有文件
from pathlib import Path
def getFile(filepath,keyword):
    folder_path = Path(filepath)  # 替换为你的目录路径
    for file in folder_path.rglob("*"):
        if file.is_file() and (keyword+".txt") in file.name:
            fPath=str(file.resolve())
            print("所需文件路径为："+fPath)

# 读取txt内容
def getContext(fPath,keyword):
    env_f=open(fPath,errors='ignore')
    for line in env_f:
        if line.__contains__(keyword): 
            print(line)
# 写入txt
def wTxt(fPath,content):
    env_f=open(fPath,mode="a")                            
    env_f.write(content+'''CNEXTBACKGROUND=yes\n  
CATNoStartDocument=no\n 
V5V4MaxSimplif=1 \n ''')
    env_f.close #写入结束
    
# 压缩文件时间戳备份,复制，粘贴 3.8.10以后支持
import shutil,time
def zipbackup(root):
    shutil.make_archive(root+"备份"+str(time.time()),'zip',root_dir=root)
    shutil.copytree(dir_setting, CATUserSettingPath, dirs_exist_ok=True) #py38开始支持dir_exsit_OK参数
    shutil.unpack_archive(CATUserSettingPath+"\CATEnv2019.zip",CATUserSettingPath)
    

# 配置颜色日志
import logging,colorlog # 需要先安装：pip install colorlog
# 配置带颜色的日志
logger = colorlog.getLogger()
logger.setLevel(logging.DEBUG)
# 定义颜色格式
formatter = colorlog.ColoredFormatter(
    "%(log_color)s%(asctime)s - %(levelname)s - %(message)s",
    log_colors={
        'DEBUG': 'cyan',
        # 'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'bold_red',
    }
)
# 添加控制台处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

# 添加文件处理器（保持原生日志格式，无颜色）
# 修改文件处理器的配置，添加encoding='utf-8'参数
file_handler = logging.FileHandler('app.log', encoding='utf-8')  # 关键修改
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)


# 获取非Unicode代码页
import ctypes;from ctypes import wintypes
def get_non_unicode_code_page():
    # 调用GetACP()函数获取ANSI代码页数值（非Unicode程序使用的编码代码页）
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    kernel32.GetACP.argtypes = []
    kernel32.GetACP.restype = wintypes.UINT
    return kernel32.GetACP()  # 直接返回代码页数值（如936、65001等）
    # 常见代码页与编码的对应关系
"""     code_page_map = {
        936: 'gbk',
        65001: 'utf-8',
        950: 'big5',
        1252: 'cp1252'
    } """

    

if __name__ == '__main__':
    print("main直接运行")
    print (dir_setting)
    # print(f"非Unicode程序编码: {get_non_unicode_code_page()}")
    import os
    os.system("chcp 65001") #import os
    # 记录不同级别的日志
    logging.debug('这是调试信息（开发时用）')
    logging.info('这是一般信息（正常运行时用）')
    logging.warning('这是警告信息（需要注意）')
    logging.error('这是错误信息（功能失败）')
    logging.critical('这是严重错误（程序可能崩溃）') 